package com.shanhesoft.java.common.ws;

import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.handshake.ServerHandshake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shanhesoft.java.common.config.RancherHostSchelduleTask;
import com.shanhesoft.java.common.config.SpringContextUtil;
import com.shanhesoft.java.common.rancher.Rancher;
import com.shanhesoft.java.common.rancher.base.TypeCollection;
import com.shanhesoft.java.common.rancher.service.HostService;
import com.shanhesoft.java.common.rancher.type.Instance;
import com.shanhesoft.java.modules.exam.service.impl.RancherService;
import com.shanhesoft.java.modules.exam.util.RancherUtils;

import retrofit2.Response;

public class HoststatsWebSocketClient extends WebSocketClient {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	public static final Map<String, ConcurrentHashMap<String, Long>> HOST_MEM_MAP = new ConcurrentHashMap<String, ConcurrentHashMap<String, Long>>();
	
	private String hostId;
	private Boolean isStopContainer = false;
	private static Rancher rancher = RancherUtils.getInstance();
	
	public HoststatsWebSocketClient(URI serverUri, Draft protocolDraft, Map<String, String> httpHeaders,
			int connectTimeout) {
		super(serverUri, protocolDraft, httpHeaders, connectTimeout);
	}

	@Override
	public void onOpen(ServerHandshake handshakedata) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onMessage(String message) {
		JSONArray jsonArray = JSON.parseArray(message);
		if(jsonArray != null && !jsonArray.isEmpty()) {
			JSONObject jsonObject = jsonArray.getJSONObject(0);
			String hostId = jsonObject.getString("id");
			long memTotal = jsonObject.getLongValue("memLimit");
			JSONObject memory = jsonObject.getJSONObject("memory");
			long usage = memory.getLongValue("usage");
			ConcurrentHashMap<String, Long> m = new ConcurrentHashMap<String, Long>();
			m.put("memTotal", memTotal);
			m.put("usage", usage);
			HOST_MEM_MAP.put(hostId, m);
//			logger.info("主机id:{},内存总量:{},已用内存:{}", hostId, memTotal, usage);
			//内存超过90%随机停止容器
			if(usage*100/memTotal >= 90 && !isStopContainer) {
				isStopContainer = true;
				stopContainer(hostId);
			}
		}
	}

	private void stopContainer(String hostId) {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					HostService hostService = rancher.type(HostService.class);
					RancherService rancherService = SpringContextUtil.getBean(RancherService.class);
					Response<TypeCollection<Instance>> execute = hostService.listInstances(hostId).execute();
					if(execute.isSuccess()) {
						List<Instance> data = execute.body().getData();
						if(data != null && data.size() > 0) {
							ConcurrentHashMap<String,Long> concurrentHashMap = HOST_MEM_MAP.get(hostId);
							Long memTotal = concurrentHashMap.get("memTotal");
							Long usage = concurrentHashMap.get("usage");
							while(usage*100/memTotal >= 80L) {
								Instance instance = data.get(new Random().nextInt(data.size()));
								String imageUuid = instance.getImageUuid();
								if(!imageUuid.startsWith("docker:rancher") && !imageUuid.contains("sonatype/nexus3")) {
									rancherService.stopContainer(instance.getId());
								}
								concurrentHashMap = HOST_MEM_MAP.get(hostId);
								memTotal = concurrentHashMap.get("memTotal");
								usage = concurrentHashMap.get("usage");
							}
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					isStopContainer = false;
				}
			}
		}).start();
	}

	@Override
	public void onClose(int code, String reason, boolean remote) {
		Map<String, HoststatsWebSocketClient> hostWsMap = RancherHostSchelduleTask.HOST_WS_MAP;
		if(!StringUtils.isEmpty(hostId)) {
			hostWsMap.remove(hostId);
			logger.info("主机websocket关闭，移除关闭主机，主机id:{}", hostId);
		}
	}

	@Override
	public void onError(Exception ex) {
		Map<String, HoststatsWebSocketClient> hostWsMap = RancherHostSchelduleTask.HOST_WS_MAP;
		if(!StringUtils.isEmpty(hostId)) {
			hostWsMap.remove(hostId);
			logger.info("主机websocket连接异常，移除关闭主机，主机id:{}", hostId);
		}
	}

	public String getHostId() {
		return hostId;
	}

	public void setHostId(String hostId) {
		this.hostId = hostId;
	}

}
